package com.feinno.urcs.group.servlet;

import com.feinno.sip.header.Contact;
import com.feinno.sip.header.SIPHeaderNames;
import com.feinno.sip.header.ims.PAssertedIdentity;
import com.feinno.sip.message.SipResponse;
import com.feinno.urcs.group.siptask.task.GroupByeArgs;
import com.feinno.urcs.group.siptask.task.GroupTaskEvents;
import com.feinno.urcs.group.siputils.URIUtils;
import com.feinno.urcs.mobile.UserLocatorService;
import com.feinno.urcs.mobile.entity.UserType;
import com.feinno.urcs.nai.IMPI;
import com.feinno.urcs.nai.IMPU;
import com.feinno.urcs.offline.RegType;
import com.feinno.urcs.offline.servlet.OfflineMessageArgs;
import com.feinno.urcs.profile.UserIdentityService;
import com.feinno.urcs.profile.entity.UserIdentity;
import com.feinno.urcs.sipservlet.SipServlet;
import com.feinno.urcs.sipservlet.SipServletException;
import com.feinno.urcs.sipservlet.SipServletRequest;
import com.feinno.urcs.types.MobileNo;
import org.helium.framework.annotations.ServiceSetter;
import org.helium.framework.annotations.TaskEvent;
import org.helium.framework.task.TaskProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sip.address.SipURI;
import javax.sip.address.URI;

/**
 * @author Li.Hongbo <lihongbo@feinno.com>
 */


public class GroupOfflineMessageServlet extends SipServlet {
	private static final Logger LOGGER = LoggerFactory.getLogger(GroupOfflineMessageServlet.class);

	@TaskEvent(GroupTaskEvents.OFFLINE_DISPATCH_TASK)
	private TaskProducer<OfflineMessageArgs> offlineDispatchTask;
	@ServiceSetter
	private UserIdentityService userIdentityService;
	@ServiceSetter
	UserLocatorService userLocatorService;
	@TaskEvent(GroupTaskEvents.UNREG_BYE)
	private TaskProducer<MobileNo> unRegByeTask;

	@Override
	protected void process(SipServletRequest request) throws SipServletException {
		try {
			if (LOGGER.isInfoEnabled()) {
				LOGGER.info(String.format("Received SipRequest: %s", request.toString()));
			}
			SipResponse response = request.createResponse(200);
			request.sendResponse(response);
			PAssertedIdentity paiHeader = (PAssertedIdentity) request.getHeader(PAssertedIdentity.NAME);
			URI uri = paiHeader.getAddress().getURI();
			if (!UserType.INNER.equals(userLocatorService.lookup(uri).getType())) {
				return;
			}
			IMPU user = IMPU.fromUri(uri);
			UserIdentity userIdentity = userIdentityService.getUserIdentityByImpu(user);
			IMPI userImpi = userIdentity.getUserImpi().getImpi();
			RegType regType;
			if (online(request)) {
				regType = RegType.REG;
			} else {
				regType = RegType.UNREG;
			}

			if (regType == RegType.UNREG) {
				String mobileNo = URIUtils.getMobileNo(user.toUri());
				unRegByeTask.produce(MobileNo.parseFrom(mobileNo));
			} else {
				OfflineMessageArgs offlineMessageArgs = new OfflineMessageArgs();
				offlineMessageArgs.setUser(user);
				offlineMessageArgs.setUserImpi(userImpi);
				offlineMessageArgs.setRegType(regType);
				offlineDispatchTask.produce(offlineMessageArgs);
			}

		} catch (Exception ex) {
			LOGGER.error(String.format("process error. Received SipRequest: %s", request.toString()), ex);
		}
	}

	private boolean online(SipServletRequest request) {
		Contact contact = (Contact) request.getHeader(SIPHeaderNames.CONTACT);
		int expires = -1;
		if (contact != null)
			expires = contact.getExpires();
		if (expires == -1 && request.getExpires() != null)
			expires = request.getExpires().getExpires();
		if (expires == -1)
			expires = 3600;
		return expires > 0;
	}
}
